const db = require('../utils/db');

module.exports = {
    /**
     * 添加二手书
     */
    async addBook(formData) {
        let res = await db.insert('book_info', formData);
        return res;
    },
    /**
     * 通过ID获取二手书信息
     */
    async getInfoById(formData) {
        let sql = `
        SELECT * FROM book_info
        WHERE book_id = '${formData.book_id}' limit 1
        `;
        let result = await db.query(sql);
        if (Array.isArray(result) && result.length > 0) {
            result = result[0];
        } else {
            result = null;
        }
        return result;
    },
    /**
     * 二手书信息修改
     */
    async modifyBookInfo(formData) {
        let res = await db.update('book_info', formData.condition, formData.info);
        return res;
    },
    /**
     * 获取二手书图片信息
     */
    async getPic(formData) {
        let sql = `
        SELECT picture_directory FROM book_info
        WHERE book_id = '${formData.book_id}' limit 1
       `;
        let result = await db.query(sql);
        if (Array.isArray(result) && result.length > 0) {
            result = result[0];
        } else {
            result = null;
        }
        return result;
    },
    /**
     * 添加二手书评论
     */
    async addEvaluate(formData) {
        let res = db.insert('book_evaluation', formData);
        return res;
    },
    /**
     * 获取二手书评论
     */
    async getEvaluate(formData) {
        let sql = `
        SELECT user_id, description, create_time FROM book_evaluation
        WHERE book_id = '${formData.book_id}'
       `;
        let res = await db.query(sql);
        return res;
    },
    // 二手书搜索
    async searchBooks(formData) {
        let sql = `
        select book_id from book_info
        where state != "已售" and name like '%${formData.name}%' 
        `;
        if (formData.tag) {
            sql += `and tag = '${formData.tag}'`;
        }
        if (formData.position) {
            sql += `and position = '${formData.position}'`;
        }
        if (formData.price) {
            sql += `order by price`
        }
        let res = await db.query(sql);
        return res;
    },
    /**
     * 二手书搜索
     */
    async recommend() {
        let sql = `
       select book_id from book_info 
       where state != "已售" limit 3
       `;
        let res = await db.query(sql);
        return res;
    }
}